package com.genexususa.eo.bing.data.requests;

import com.genexususa.eo.bing.CampaignManagementServiceClasses.SitePlacement;
import com.genexususa.eo.bing.data.GxItemException;
import com.genexususa.eo.bing.data.wsSubclasses.GxSitePlacement;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class GxSitePlacementsAdGroupRequest {
    private long gxAdGroupId;
    private long bingAdGroupId;
    private SitePlacement[] sitePlacements;

    public GxSitePlacementsAdGroupRequest(Element element) throws IllegalArgumentException, GxItemException {
        if (element.getElementsByTagName("GxAdGroupId").getLength() > 0 &&
            element.getElementsByTagName("GxAdGroupId").item(0).getChildNodes().getLength() > 0 &&
            Long.valueOf(((Node)element.getElementsByTagName("GxAdGroupId").item(0).getChildNodes().item(0)).getNodeValue()) != 0) {
            this.gxAdGroupId = Long.valueOf(((Node)element.getElementsByTagName("GxAdGroupId").item(0).getChildNodes().item(0)).getNodeValue());
        } else {
            throw new GxItemException("Missing external AdGroup id");
        }
        if (element.getElementsByTagName("BingAdGroupId").getLength() > 0 &&
            element.getElementsByTagName("BingAdGroupId").item(0).getChildNodes().getLength() > 0 &&
            Long.valueOf(((Node)element.getElementsByTagName("BingAdGroupId").item(0).getChildNodes().item(0)).getNodeValue()) != 0) {
            this.bingAdGroupId = Long.valueOf(((Node) element.getElementsByTagName("BingAdGroupId").item(0).getChildNodes().item(0)).getNodeValue());
        } else {
            throw new GxItemException("Missing Bing AdGroup id");
        }
        NodeList sitePlacementsNode = element.getElementsByTagName("SitePlacementCollection");
        if (sitePlacementsNode.getLength() > 0) {
            NodeList sitePlacementNode = ((Element)sitePlacementsNode.item(0)).getElementsByTagName("SitePlacement");
            this.sitePlacements = new SitePlacement[sitePlacementNode.getLength()];
            for (int i=0; i<sitePlacementNode.getLength(); i++) {
                sitePlacements[i] = new GxSitePlacement((Element)sitePlacementNode.item(i));
            }
        } else {
            throw new GxItemException("No SitePlacements were found for AdGroup " + this.gxAdGroupId);
        }
    }

    public long getGxAdGroupId() {
        return gxAdGroupId;
    }

    public long getBingAdGroupId() {
        return bingAdGroupId;
    }

    public SitePlacement[] getSitePlacements() {
        return sitePlacements;
    }
}
